import 'package:flutter/material.dart';
import 'package:fsharing/core/models/store_categories.dart';
import 'package:fsharing/core/models/store_detail.dart';
import 'package:fsharing/core/viewmodels/app_model.dart';
import 'package:fsharing/core/viewmodels/pages/store/store_detail_model.dart';
import 'package:fsharing/core/viewmodels/pages/store/store_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/ui/pages/store/store_area_page.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:provider/provider.dart';

class StorePageArgs {
  final int storeId;
  final int storeAreaId;

  StorePageArgs(this.storeId, this.storeAreaId);
}

/// Common Page
class StorePage extends StatelessWidget {
  final StorePageArgs args;

  StorePage({
    Key key,
    this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => StoreDetailModel(
        Provider.of(context, listen: false),
      )..storeId = args.storeId,
      child: BackgroundContainer(
        child: Consumer<StoreDetailModel>(
          builder: (context, model, child) {
            switch (model.viewState) {
              case ViewState.busy:
                return Scaffold(
                  appBar: child,
                  body: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              case ViewState.error:
                return Scaffold(
                  appBar: child,
                  body: Center(
                    child: Text(model.errorMessage),
                  ),
                );
              case ViewState.success:
                return Scaffold(
                  appBar: AppBar(
                    leading: RoundBackButton(),
                    title: Text(model.storeDetail.storeName),
                  ),
                  body: _BodyWidget(
                    storeAreaId: args?.storeAreaId,
                    storeDetail: model.storeDetail,
                  ),
                );
              default:
                return Container();
            }
          },
          child: AppBar(
            leading: RoundBackButton(),
            title: Text('店铺'),
          ),
        ),
      ),
    );
  }
}

/// Tab Item Page
class StoreTabItemPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProxyProvider<AppStoreModel, StoreDetailModel>(
      create: (context) => StoreDetailModel(Provider.of(context, listen: false)),
      update: (_, appStoreModel, model) => model..storeId = appStoreModel.currentStoreId,
      child: Consumer<StoreDetailModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return Scaffold(
                appBar: AppBar(
                  title: Text(model.storeDetail.storeName),
                ),
                body: _BodyWidget(
                  storeAreaId: 0,
                  storeDetail: model.storeDetail,
                ),
              );
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _BodyWidget extends StatelessWidget {
  final int storeAreaId;
  final StoreDetail storeDetail;

  _BodyWidget({
    Key key,
    @required this.storeAreaId,
    @required this.storeDetail,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<MapEntry<String, String>> list = storeDetail.storeAreaIdNameMap.entries.toList();
    list.insert(0, MapEntry('0', '全部'));
    // 商区位置
    var index = list.indexWhere((mapEntry) => mapEntry.key == '$storeAreaId');
    if (index == -1) {
      index = 0;
    }
    return ChangeNotifierProvider(
      create: (context) => StoreModel(),
      child: DefaultTabController(
        length: list.length,
        initialIndex: index,
        child: Column(
          children: <Widget>[
            Container(
              alignment: Alignment.centerLeft,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/store/img_header.png'),
                  fit: BoxFit.fill,
                ),
              ),
              height: 80,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  _CategoryWidget(),
                  Container(
                    height: 20,
                    margin: EdgeInsets.symmetric(horizontal: 6),
                    child: TabBar(
                      isScrollable: true,
                      indicator: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('assets/images/store/img_tab_selected.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                      indicatorSize: TabBarIndicatorSize.label,
                      labelPadding: EdgeInsets.symmetric(horizontal: 10),
                      indicatorWeight: 0,
                      tabs: List.generate(list.length, (index) {
                        return Tab(
                          child: Container(
                            alignment: Alignment.center,
                            padding: EdgeInsets.symmetric(horizontal: 10),
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                image: AssetImage('assets/images/store/img_tab_normal.png'),
                                fit: BoxFit.fill,
                              ),
                            ),
                            constraints: BoxConstraints(minWidth: 70, minHeight: 20),
                            child: Text(
                              list[index].value,
                              style: TextStyle(fontSize: 13),
                            ),
                          ),
                        );
                      }),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: TabBarView(
                children: List.generate(list.length, (index) {
                  StoreDetailModel model = Provider.of(context, listen: false);
                  return StoreAreaPage(
                    storeId: model.storeId,
                    storeAreaId: int.parse(list[index].key),
                  );
                }),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _CategoryWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16),
        child: Consumer<StoreModel>(
          builder: (context, model, child) {
            final name = model.category?.name ?? '全部';
            return Row(
              children: <Widget>[
                Text(
                  '商品分类：',
                  style: TextStyle(fontSize: 15),
                ),
                Container(
                  padding: EdgeInsets.symmetric(vertical: 2, horizontal: 8),
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/images/store/img_tab_selected.png'),
                      fit: BoxFit.fill,
                    ),
                  ),
                  child: Text(
                    '$name >',
                    style: TextStyle(fontSize: 13),
                  ),
                ),
              ],
            );
          },
        ),
      ),
      onTap: () {
        _onCategoryClicked(context);
      },
    );
  }

  void _onCategoryClicked(BuildContext context) async {
    StoreDetailModel model = Provider.of(context, listen: false);
    var result = await Navigator.of(context).pushNamed('/store/category', arguments: model.storeId);
    if (result is Category) {
      StoreModel storeModel = Provider.of(context, listen: false);
      storeModel.category = result;
    }
  }
}
